package com.applet.applet_shangcheng.service;

import com.alibaba.fastjson.JSONObject;
import com.applet.applet_shangcheng.dao.GoodsMapper;
import com.applet.applet_shangcheng.dao.UserMapper;
import com.applet.applet_shangcheng.entity.Goods;
import com.applet.applet_shangcheng.entity.Order;
import com.applet.applet_shangcheng.utlis.*;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.applet.applet_shangcheng.utlis.AppletUtil.getRandomStringByLength;

@Service
@Transactional
public class PayService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UserMapper userMapper;
    @Value("${applet.path.domain}")

    String appID = "wx24e555c077e702f3";
    String mchID = "1582954481";
    String appSecret = "da2f185559d5d14e0d98ae268d7deb7b";
    String key = "washimayun1302525820515014354439";
    //申请授权码地址
    String wxOAuth2RequestUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
    //授权回调地址
//    String wxOAuth2CodeReturnUrl = "http://29t934420o.wicp.vip:48415/weixin/pay/notify";
    String wxOAuth2CodeReturnUrl = "http://29t934420o.wicp.vip:16943/notify";
    private String domain;
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> selectNative(String order_id) {
        try {
            //统一下单地url
            String pay_url = "https://api.mch.weixin.qq.com/pay/orderquery";
            //入参,将数据封装到map转xml
            Map<String,String>data= new HashMap<>();
            data.put("appid", WXConstVO.appId);// 小程序ID
            data.put("mch_id", WXConstVO.mch_id);// 商户号
            data.put("out_trade_no", order_id);         //商户订单号
            data.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串

            //data.put("openid", WXConstVO.);//用户标识
            String signedXml = WXPayUtil.generateSignedXml(data, WXConstVO.key);//xml

            //请求:httpclient
            HttpClient httpClient = new HttpClient(pay_url);
            httpClient.setXmlParam(signedXml);//请求参数
            httpClient.setHttps(true);        //请求方式
            httpClient.post();

            //响应结果xml转map
            String strXml = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(strXml);
            map.put("order_id", order_id);
            String return_code = map.get("result_code");
            if (return_code.equals("FAIL")) {
                return  map;
            }
            String trade_state_desc = map.get("trade_state_desc");
            if (trade_state_desc.equals("订单未支付")){
                return  map;
            }
            Order order = orderService.findByOrderId(order_id);
            if (order != null) {
                order.setOrderStatus(1);
                order.setPayStatus(1);
                order.setPayTime(new Date());
                orderService.save(order);
                int sumNumber = order.getSumNumber();
                String goodsID1 = order.getGoodsID();
                goodsMapper.updateGoodsNumber(sumNumber,goodsID1);
                String code = order.getCode();
                String goodsID = order.getGoodsID();
                if (code != null&&goodsID != null) {
                    Goods goods = goodsMapper.findGoods(Integer.valueOf(goodsID));
                    int integral = goods.getIntegral();
                    userMapper.save(code,integral);
                }
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object>   createNative(String order_id, String unit_price,String spbill_create_ip) throws Exception {

        String pay_url = WXConstVO.pay_url;
        //入参,将数据封装到map转xml
        Map<String,String>data= new HashMap<>();
        data.put("appid", WXConstVO.appId);// 小程序ID
        data.put("mch_id", WXConstVO.mch_id);// 商户号
        data.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
        data.put("body", "小程序支付");              //商品描述
        data.put("out_trade_no", order_id);         //商户订单号
        data.put("total_fee", unit_price);// 订单总金额，单位为分
        data.put("spbill_create_ip", spbill_create_ip);//终端IP
        data.put("notify_url", wxOAuth2CodeReturnUrl);// 回调地址
        data.put("trade_type", "JSAPI");//交易类型NATIVE,JSAPI
        //data.put("openid", WXConstVO.);//用户标识
        data.put("openid", "oKbmB4k_N4bdggUI_95A1uDZbPLg");//用户标识
        String signedXml = WXPayUtil.generateSignedXml(data,WXConstVO.key);//xml

        System.out.println(order_id+"+"+unit_price);
        //请求:httpclient
        HttpClient httpClient = new HttpClient(pay_url);
        httpClient.setXmlParam(signedXml);//请求参数
        httpClient.setHttps(true);        //请求方式
        httpClient.post();

        //响应结果xml转map
        String strXml = httpClient.getContent();
        Map<String, String> map = WXPayUtil.xmlToMap(strXml);
        System.out.println(map);
        /* map.put("code_url",map.get("code_url"));*/
        map.put("out_trade_no",order_id);
        map.put("total_fee",unit_price);

        String return_code = (String) map.get("return_code");//返回状态码
        String result_code = (String) map.get("result_code");//返回状态码
        //生成的随机字符串
        String nonce_str = getRandomStringByLength(32);
        Map<String, Object> response = new HashMap<String, Object>();//返回给小程序端需要的参数
        if (return_code .equals("SUCCESS")  && result_code.equals("SUCCESS")) {
            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
            response.put("nonceStr", nonce_str);
            response.put("package", "prepay_id=" + prepay_id);
            Long timeStamp = System.currentTimeMillis() / 1000;
            response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
            //拼接签名需要的参数
            String stringSignTemp = "appId=" +appID + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
            String paySign = PayUtil.sign(stringSignTemp, key, "utf-8").toUpperCase();
            response.put("paySign", paySign);
        }
        response.put("appID", appID);
        response.put("orderid", order_id);
        return response;
    }

        /*try {
            //统一下单地url
            String pay_url = WXConstVO.pay_url;
            //入参,将数据封装到map转xml
            Map<String,String>data= new HashMap<>();
            data.put("appid", WXConstVO.appId);// 小程序ID
            data.put("mch_id", WXConstVO.mch_id);// 商户号
            data.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
            data.put("body", "小程序支付");              //商品描述
            data.put("out_trade_no", order_id);         //商户订单号
            data.put("total_fee", unit_price);// 订单总金额，单位为分
            data.put("spbill_create_ip", spbill_create_ip);//终端IP
//            data.put("notify_url", WXConstVO.notify_url);// 回调地址
            data.put("notify_url",domain+ "/weixin/pay/notify");// 回调地址
            data.put("trade_type", "JSAPI");//交易类型NATIVE,JSAPI
            //data.put("openid", WXConstVO.);//用户标识
            data.put("openid", "oKbmB4k_N4bdggUI_95A1uDZbPLg");//用户标识
            String signedXml = WXPayUtil.generateSignedXml(data, WXConstVO.key);//xml

            //请求:httpclient
            HttpClient httpClient = new HttpClient(pay_url);
            httpClient.setXmlParam(signedXml);//请求参数
            httpClient.setHttps(true);        //请求方式
            httpClient.post();

            //响应结果xml转map
            String strXml = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(strXml);
            map.put("order_id", order_id);
            map.put("unit_price", unit_price);
            map.put("spbill_create_ip", spbill_create_ip);
            String prepayId = (String) map.get("prepay_id");
            if (prepayId==null){
                return map;
            }
            System.out.println(prepayId);
            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("appId",WXConstVO.appId);
            String timeStamp =System.currentTimeMillis()/1000 + "";
            payMap.put("timeStamp",timeStamp);
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            String signedXmlPay = WXPayUtil.generateSignedXml(payMap, WXConstVO.key);//xml
// 6. 将这个6个参数传给前端
            System.out.println(signedXmlPay);
            return payMap;
            //return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;*/


    //获取openid
    @Transactional(rollbackFor = Exception.class)
    public  Map<String,String> getOpenId(String code) {
        try {

            String appid ="wx24e555c077e702f3";
            String secret ="da2f185559d5d14e0d98ae268d7deb7b";
            String ulr ="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
            Map<String,String>data= new HashMap<>();
            data.put("appid","wx24e555c077e702f3");
            data.put("secret","da2f185559d5d14e0d98ae268d7deb7b");
            data.put("js_code","102");
            data.put("grant_type","authorization_code");
            String signedXml = WXPayUtil.generateSignedXml(data, WXConstVO.key);
            HttpClient httpClient = new HttpClient(ulr);
            httpClient.setXmlParam(signedXml);//请求参数
            httpClient.setHttps(true);        //请求方式
            httpClient.post();
            String strXml = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(strXml);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        JSONObject header = new JSONObject()
//                .fluentPut("TIMESTAMP",System.currentTimeMillis()/1000 + "");
 String data =System.currentTimeMillis()/1000 + "";
        System.out.println(data);
    }
}
